package net.tngou.iask.action.api;

import java.lang.reflect.InvocationTargetException;
import java.sql.Timestamp;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.math.NumberUtils;

import net.tngou.iask.action.BaseAction;
import net.tngou.iask.enums.LevelEnum;
import net.tngou.iask.pojo.Access;
import net.tngou.iask.pojo.Accessresult;
import net.tngou.iask.pojo.Answer;
import net.tngou.iask.pojo.Cure;
import net.tngou.iask.pojo.Health;
import net.tngou.iask.pojo.Obituary;
import net.tngou.iask.pojo.POJO;
import net.tngou.iask.pojo.Patient;
import net.tngou.iask.pojo.Question;
import net.tngou.iask.pojo.Survey;
import net.tngou.iask.pojo.Survey_question;
import net.tngou.iask.service.AccessService;
import net.tngou.iask.service.AdviceService;
import net.tngou.iask.service.AnswerService;
import net.tngou.iask.service.CureService;
import net.tngou.iask.service.QuestionService;
import net.tngou.iask.util.DateUtil;
import net.tngou.iask.util.StringUtil;

/**
 * 访问记录
 * @author tngou@tngou.net
 *
 */
public class AccessApi extends BaseAction {

	/**
	 * 添加访问记录
	 */
	public void add() {
		if(user==null){
			run_nologin();return;
		}
		if((user.getRole()!=3&&user.getRole()!=4&&user.getRole()!=5&&user.getRole()!=6)||user.getMain()==0)
		{
			run_false("没有添加权限");return;
		}
		Access access = getAsk(Access.class);
		Patient patient = new Patient().get(access.getPatient());
		long id =0;
		switch (access.getType()) {
		case 1:
			if(access.getPatient()==0||access.getSurvey()==0)
			{
				run_false("请求的参数不正确！");return;
			}			
			Survey survey = new Survey().get(access.getSurvey());
			if(patient==null||survey==null||(survey.getType()==2&&access.getCure()==0))
			{
				run_false("请求的数据不正确！");return;
			}	
			access.setMain(user.getMain());
			id = access.save();
			
			break;
		case 2:
			if(access.getPatient()==0||access.getCure()==0)
			{
				run_false("请求的参数不正确！");return;
			}
			Cure  cure= new Cure().get(access.getCure());
			if(patient==null||cure==null)
			{
				run_false("请求的数据不正确！");return;
			}
			CureService service = new CureService();
			id = service.saveAccess(cure, cure.getSurvey());
			break;
		default:
			break;
		}
		
		if(id>0){
			saveLog(LevelEnum.work, "添加访问记录(id:"+id+"-"+patient.getName()+")");
			run_success(id+"");
		}
		else run_false("添加失败！");
	}
	
	/**
	 * 死亡记录
	 */
	public void death() {
		Obituary bean=getAsk(Obituary.class);
		if(bean.getAccess()==0||bean.getDeathstamp()==null)
		{
			run_false("请求的参数不正确！");return;
		}
		Access access = new Access().get(bean.getAccess());
		if(access==null)
		{
			run_false("请求的数据不正确！");return;
		}
		bean.setPatient(access.getPatient());
		if(user!=null)bean.setUser(user.getId());
		long id = bean.save();
		if(id>0)
		{
			int usetime=10*1000;//默认20秒
			String ut = request.getParameter("usetime");
			if(ut!=null&&NumberUtils.isNumber(ut)){
				usetime=Integer.parseInt(ut);
			}
			access.setUsetime(access.getUsetime()+usetime);//++1
			access.setSpeed(5);
			access.setTotal(5);
			access.setState(2);//						
			access.setEndtime(new Timestamp(new Date().getTime()));//设置结束时间	
			access.update();
			run_success("数据提交成功！");
		}else
		{
			run_success("数据提交失败！");
		}
	}
	
	/**
	 * 生存状态
	 */
	public void alive()
	{
		String access_s = request.getParameter("access");	
		String alive=request.getParameter("alive");
		if(isEmpty(access_s,alive)||!NumberUtils.isNumber(access_s)||!NumberUtils.isNumber(alive))
		{
			run_false("请求的参数不正确！");return;
		}
		Access access = new Access().get(Long.parseLong(access_s));
		if(access==null)
		{
			run_false("请求的数据不正确！");return;
		}
		int usetime=10*1000;//默认20秒
		String ut = request.getParameter("usetime");
		if(ut!=null&&NumberUtils.isNumber(ut)){
			usetime=Integer.parseInt(ut);
		}
		access.setUsetime(access.getUsetime()+usetime);//++1
		access.setAlive(Integer.parseInt(alive));		
		long id = access.update();
		if(id>0)
		{
			if(access.getAlive()==-1)
			{
				Patient patient = new  Patient().get(access.getPatient());
				if(patient!=null){patient.setAlive(-1);patient.update();}
			}
			run_success("数据提交成功！");
		}else
		{
			run_success("数据提交失败！");
		}
	}
	
	/**
	 * 开始进行访问
	 */
	public void start() {
		
		String access_s = request.getParameter("access");	
		String relation=request.getParameter("relation");
		if(isEmpty(access_s,relation)||!NumberUtils.isNumber(access_s)||!NumberUtils.isNumber(relation))
		{
			run_false("请求的参数不正确！");return;
		}
		Access access = new Access().get(Long.parseLong(access_s));
		if(access==null)
		{
			run_false("请求的数据不正确！");return;
		}
		Survey survey = new Survey().get(access.getSurvey());
		if(survey==null)
		{
			run_false("请求的数据不正确！");return;
		}
		QuestionService questionService = new QuestionService();
		List<Question> list = questionService.getQuestion(survey.getId());
		if(list==null||list.size()==0)
		{
			run_false("请求的数据不正确！");return;
		}
		int usetime=10*1000;//默认20秒
		String ut = request.getParameter("usetime");
		if(ut!=null&&NumberUtils.isNumber(ut)){
			usetime=Integer.parseInt(ut);
		}
		access.setUsetime(access.getUsetime()+usetime);//++1
		access.setState(1);//进行
		access.setQuestion(list.get(0).getId());
		access.setTotal(list.size());
		access.setRelation(Integer.parseInt(relation));
		if(access.getRelation()==0)access.setAlive(1);
		access.setStarttime(new Timestamp(new Date().getTime()));
		if(user!=null)access.setUser(user.getId());
		long id = access.update();
		if(id>0)
		{
			run_success("数据提交成功！");
		}else
		{
			run_success("数据提交失败！");
		}
			
		
	}
	
	/**
	 * 更新随访
	 */
	public void update() {
		String access_s = request.getParameter("access");	
		if(isEmpty(access_s)||!NumberUtils.isNumber(access_s))
		{
			run_false("请求的参数不正确！");return;
		}
		Access access = new Access().get(Long.parseLong(access_s));
		if(access==null)
		{
			run_false("请求的数据不正确！");return;
		}
		int usetime=10*1000;//默认20秒
		String ut = request.getParameter("usetime");
		if(ut!=null&&NumberUtils.isNumber(ut)){
			usetime=Integer.parseInt(ut);
		}
		Accessresult result= new Accessresult();
		result.setPatient(access.getPatient());
		result.setAccess(access.getId());
		Enumeration<String> sts = request.getParameterNames();
		AccessService accessService = new AccessService();
		while (sts.hasMoreElements()) {
			String s = sts.nextElement();
			if(NumberUtils.isNumber(s))
			{
				Question question=new Question().get(Long.parseLong(s));
				if(question!=null)
				{
					int t = question.getType();
					result.setQuestion(question.getId());
					result.setName(question.getName());
					@SuppressWarnings("serial")
					POJO pojo = new Health().get(new HashMap<String,Object>(){{
							put("question", question.getId());
							put("patient", access.getPatient());
					}});
					QuestionService service = new QuestionService();
					List<Answer> answers = service.getAnswer(question.getId());
					String value=null;
					switch (t) {
					case 0:							
						value = request.getParameter(s);
						if(value!=null&&NumberUtils.isNumber(value))
						{
							if(1==Integer.parseInt(value))
							{
								result.setValue(1);
								result.setDescription("是");
								
							}else
							{
								result.setValue(0);
								result.setDescription("否");
							}
							accessService.save(pojo, result);
						}
						break;
					case 1:							
						value = request.getParameter(s);
						if(value!=null&&NumberUtils.isNumber(value))
						{
							for (Answer answer : answers) {
								if(answer.getValue()==Integer.parseInt(value))
								{
									result.setDescription(answer.getName());
									result.setValue(answer.getValue());
								}
							}			
							accessService.save(pojo, result);
						}
						break;	
					case 2:
						String[] values=request.getParameterValues(s);
						if(values!=null)
						{
							new Accessresult().delete("access="+result.getAccess()+" AND question="+result.getQuestion());
							new Health().delete("patient="+result.getPatient()+" AND question="+result.getQuestion());//先删除数据
							for (String v : values) {
								if(NumberUtils.isNumber(v))
								{
									Accessresult r= new Accessresult();
									r.setAccess(result.getAccess());
									r.setQuestion(result.getQuestion());
									r.setPatient(result.getPatient());
									r.setName(question.getName());
									r.setValue(Integer.parseInt(v));
									answers.forEach(e->{
										if(e.getValue()==r.getValue())r.setDescription(e.getName());
									});
									accessService.save(null, r);
								}
							}
						}
						break;
					case 3://填空（数字）
						value = request.getParameter(s);
						if(value!=null&&NumberUtils.isNumber(value))
						{
							for (Answer answer : answers) {
//								if(answer.getValue()==Integer.parseInt(value))
//								{
									result.setDescription(Integer.parseInt(value)+answer.getName());
									result.setValue(Integer.parseInt(value));
//								}
							}
							accessService.save(pojo, result);
						}
						break;
					case 4://填空（备注）
						value = request.getParameter(s);
						if(StringUtil.isNotEmpty(value))
						{
							result.setDescription(value);	
							accessService.save(pojo, result);
						}
						break;
					default:
						break;
					}
					
				}
			}	
        }
		access.setUsetime(access.getUsetime()+usetime);//++1
		access.setSpeed(access.getTotal());
		access.setQuestion(0);
		access.setState(2);//						
		access.setEndtime(new Timestamp(new Date().getTime()));//设置结束时间	
		long id = access.update();
		if(id>0)
		{
			new AdviceService().setAdvice(access);//更新建议
			run_success("数据提交成功！");
		}else
		{
			run_false("数据提交失败！");
		}
	}
	
	/**
	 * 问卷接受
	 */
	public void ask() {
//		if(user==null){
//			run_nologin();return;
//		}

		String access_s = request.getParameter("access");	
		if(isEmpty(access_s)||!NumberUtils.isNumber(access_s))
		{
			run_false("请求的参数不正确！");return;
		}
		Access access = new Access().get(Long.parseLong(access_s));
		if(access==null)
		{
			run_false("请求的数据不正确！");return;
		}
		Survey survey = new Survey().get(access.getSurvey());
		if(survey==null)
		{
			run_false("请求的数据不正确！");return;
		}
		QuestionService questionService = new QuestionService();
		List<Question> list = questionService.getQuestion(survey.getId());
		if(list==null||list.size()==0)
		{
			run_false("请求的数据不正确！");return;
		}

//		if(access.getType()==1)//健康档案
//		{
		Accessresult result =getAsk(Accessresult.class);
		result.setAccess(access.getId());
		result.setPatient(access.getPatient());
		if(result.getQuestion()==0)
		{
			run_false("请求的参数不正确！");return;
		}
		Patient patient = new Patient().get(result.getPatient());
		Question question = new Question().get(result.getQuestion());
		if(patient==null||question==null)
		{
			run_false("请求的数据不正确！");return;
		}
		result.setName(question.getName());
		int t = question.getType();
		@SuppressWarnings("serial")
		POJO pojo = new Health().get(new HashMap<String,Object>(){{
				put("question", result.getQuestion());
				put("patient", result.getPatient());
		}});
		QuestionService service = new QuestionService();
		AccessService accessService = new AccessService();
		List<Answer> answers = service.getAnswer(question.getId());
		long id=0;
		switch (t) {
		case 0://判断
			
			if(result.getValue()==0)
			{
				result.setDescription("否");
			}else
			{
				result.setValue(1);
				result.setDescription("是");
			}
			id = accessService.save(pojo, result);

			break;
			case 1://单选
				result.setName(question.getName());		
				answers.forEach(e->{
					if(e.getValue()==result.getValue())result.setDescription(e.getName());
				});				
				id = accessService.save(pojo, result);

				break;
			case 2://多选
				String[] values=request.getParameterValues("values");
				if(values!=null)
				{
					new Accessresult().delete("access="+result.getAccess()+" AND question="+result.getQuestion());
					new Health().delete("patient="+result.getPatient()+" AND question="+result.getQuestion());//先删除数据
					for (String value : values) {
						if(NumberUtils.isNumber(value))
						{
							Accessresult r= new Accessresult();
							r.setAccess(result.getAccess());
							r.setQuestion(result.getQuestion());
							r.setPatient(result.getPatient());
							r.setName(question.getName());
							r.setValue(Integer.parseInt(value));
							answers.forEach(e->{
								if(e.getValue()==r.getValue())r.setDescription(e.getName());
							});
							id = accessService.save(null, r);
						}
					}
				}
				break;
			case 3://填空（数字）
				answers.forEach(e->{
					result.setDescription(result.getValue()+e.getName());
				});
				id = accessService.save(pojo, result);
				break;
			case 4://填空（备注）
				if(StringUtil.isNotEmpty(result.getDescription()))
				{
					result.setName(question.getName());
					id = accessService.save(pojo, result);
				}
				break;
			default:
				break;
			}
			
			if(id>0)
			{
				int usetime=10*1000;//默认20秒
				String ut = request.getParameter("usetime");
				if(ut!=null&&NumberUtils.isNumber(ut)){
					usetime=Integer.parseInt(ut);
				}
				access.setUsetime(access.getUsetime()+usetime);//++1
				access.setSpeed(access.getSpeed()+1);//++1
				for (int i = 0; i < list.size(); i++) {
					if(list.get(i).getId()==result.getQuestion())
					{
						
						if((i+1)==list.size())//完成
						{
							access.setQuestion(0);
							access.setState(2);//						
							access.setEndtime(new Timestamp(new Date().getTime()));//设置结束时间	
						}else
						{
							access.setQuestion(list.get(i+1).getId());
						}
					}
				}
				access.update();
				if(access.getState()==2)//完成时更新建议
				{
					new AdviceService().setAdvice(access);//更新建议
				}
				run_success("数据提交成功！");
				
			}else
			{
				run_false("数据提交失败！");
			}
			
			
//		}else
//		{
//			run_false("请求的参数不正确！");
//		}
		
	}
	
	/**
	 * 保存到健康文档
	 * @param pojo
	 * @param result
	 */
	private void _saveHealth(POJO pojo ,Accessresult result)
	{
		
		
		try {
			Health health=new Health();
			BeanUtils.copyProperties(health, result);
			if(pojo==null)
			{
				health.setId(0);
				health.save();
			}else
			{
				health.setId(pojo.getId());
				health.update();
			}
		} catch (IllegalAccessException | InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		
	}
}
